﻿using System;
using System.IO;
using System.Reflection;
using System.Xml;

namespace PlaxoSyncWM {
    public class Settings {
        private static string configPath;

        internal Settings() {
            configPath = String.Format("{0}.config", Assembly.GetExecutingAssembly().GetName().CodeBase);
        }

        public string GetSetting(string settingName) {
            XmlDocument settings = new XmlDocument();
            XmlTextReader sr;
            using (FileStream fsr = new FileStream(configPath, FileMode.Open, FileAccess.Read)) {
                sr = new XmlTextReader(fsr);
                settings.Load(sr);
                sr.Close();
            }
            foreach (XmlNode node in settings["configuration"]["appSettings"]) {
                if (string.Compare(settingName, node.Attributes["key"].Value) == 0)
                    return node.Attributes["value"].Value;
            }
            return "";
        }

        public void SaveSetting(string settingName, string settingValue) {
            XmlDocument settings = new XmlDocument();
            XmlTextReader sr;
            using (FileStream fsr = new FileStream(configPath, FileMode.Open, FileAccess.ReadWrite)) {
                sr = new XmlTextReader(fsr);
                settings.Load(sr);
                sr.Close();
            }
            foreach (XmlNode node in settings["configuration"]["appSettings"]) {
                if (string.Compare(settingName, node.Attributes["key"].Value) == 0)
                    node.Attributes["value"].Value = settingValue;
            }
            settings.Save(configPath);
        }

        public bool Exist() {
            if (GetSetting("loginSuccessful").Equals("y"))
                return true;
            else return false;
        }
    }
}